﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Data;

namespace MoneyBook.Windows.Data {
    public abstract class BindingListener<T> {

        private DependencyProperty property = null;
        private DependencyObject target = null;

        public event EventHandler<BindingValueChangedEventArgs<T>> BindingValueChanged;

        protected BindingListener(DependencyObject target) {
            if (target == null) {
                throw new ArgumentNullException("target");
            }
            this.property = DependencyProperty.Register("Listener", typeof(T), typeof(DependencyObject), new PropertyMetadata(OnListenerChanged));
            this.target = target;
        }

        protected abstract Binding GetBinding();

        protected bool IsListening { get; private set; }

        protected virtual void OnBindingValueChagned(T newValue, T oldValue) {
            if (this.BindingValueChanged != null) {
                this.BindingValueChanged(this, new BindingValueChangedEventArgs<T>(newValue, oldValue));
            }
        }

        private void OnListenerChanged(object sender, DependencyPropertyChangedEventArgs e) {
            OnBindingValueChagned((T)e.NewValue,(T)e.OldValue);
        }

        public void Listen() {
            if (this.IsListening) {
                //TODO : message
                throw new InvalidOperationException();
            }
            Binding binding = this.GetBinding();
            if (binding == null) {
                //TODO : message
                throw new InvalidOperationException();
            }

            BindingOperations.SetBinding(this.target, this.property, binding);
            this.IsListening = true;
        }

    }
}
